package com.haierCamera.customapplication.ui.main;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;

import com.haierCamera.customapplication.BaseActivity;
import com.haierCamera.customapplication.R;
import com.haierCamera.customapplication.api.vo.RecordGroupItem;
import com.haierCamera.customapplication.databinding.HzklActivityRecordListAllBinding;
import com.haierCamera.customapplication.ui.business.Business;
import com.haierCamera.customapplication.ui.business.entity.RecordInfo;
import com.haierCamera.customapplication.ui.main.widget.CustomDatePickerDialogFragment;
import com.haierCamera.customapplication.ui.main.widget.DrawableCenterTextView;
import com.haierCamera.customapplication.ui.mediaplay.MediaPlayActivity;
import com.haierCamera.customapplication.utils.DateUtil;
import com.haierCamera.customapplication.utils.DensityUtil;
import com.kunminx.linkage.adapter.viewholder.LinkageSecondaryFooterViewHolder;
import com.kunminx.linkage.adapter.viewholder.LinkageSecondaryHeaderViewHolder;
import com.kunminx.linkage.adapter.viewholder.LinkageSecondaryViewHolder;
import com.kunminx.linkage.bean.BaseGroupedItem;
import com.kunminx.linkage.contract.ILinkageSecondaryAdapterConfig;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;

public class HZKLRecordListAllActivity extends BaseActivity implements CustomDatePickerDialogFragment.OnSelectedDateListener{

    HzklActivityRecordListAllBinding binding;
    List<RecordGroupItem> mList = new ArrayList<>();
    ElemeSecondaryAdapterConfig sac;
    String containHour = "";
    int dayBefore = 0;
    int channel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = DataBindingUtil.setContentView(this, R.layout.hzkl_activity_record_list_all);
        binding.imgReturn.setOnClickListener((v)->{
            finish();
        });

        binding.tvDate.setOnClickListener((v)->{
            showDatePickDialog();
        });

        channel = getIntent().getIntExtra("channelId",0);
        binding.ivLast.setOnClickListener((v)->{
            dayBefore ++;
            containHour = "";
            mList.clear();
            binding.tvDate.setText(DateUtil.getSeveralBefore(dayBefore).substring(0,10));
            if (dayBefore >= 1) {
                binding.ivNext.setImageResource(R.drawable.hzkl_day_next_click);
                binding.ivNext.setClickable(true);
            }
            getRecordList(getIntent().getStringExtra("devId"),getIntent().getStringExtra("cameraPwd")
                    ,DateUtil.getSeveralBefore(dayBefore).substring(0,10) + " 00:00:00"
                    ,DateUtil.getSeveralBefore(dayBefore).substring(0,10) + " 23:59:59");
        });
        binding.ivNext.setOnClickListener((v)->{
            dayBefore --;
            containHour = "";
            mList.clear();
            binding.tvDate.setText(DateUtil.getSeveralBefore(dayBefore).substring(0,10));
            if (dayBefore == 0) {
                binding.ivNext.setImageResource(R.drawable.hzkl_day_next_no);
                binding.ivNext.setClickable(false);
            }
            getRecordList(getIntent().getStringExtra("devId"),getIntent().getStringExtra("cameraPwd")
                    ,DateUtil.getSeveralBefore(dayBefore).substring(0,10) + " 00:00:00"
                    ,DateUtil.getSeveralBefore(dayBefore).substring(0,10) + " 23:59:59");
        });
        sac = new ElemeSecondaryAdapterConfig();
        sac.setContext(this);
        sac.setActivity(this);
        binding.lkRcv.initAdapterConfig(sac);

        binding.tvDate.setText(DateUtil.getNowTime().substring(0,10) + "");
        binding.ivNext.setClickable(false);
        getRecordList(getIntent().getStringExtra("devId"),getIntent().getStringExtra("cameraPwd")
                ,DateUtil.getNowTime().substring(0,10) + " 00:00:00"
                ,DateUtil.getNowTime().substring(0,10) + " 23:59:59");
    }

    private void getRecordList(String deviceId,String cameraPwd,String startTime,String endTime) {
        Log.i("TAG","getRecordList-from-" + startTime + "/" + "to-" + endTime);
        showLoadingDialog("加载中");
        Business.getInstance().queryRecordList2(deviceId
                ,cameraPwd
                , startTime
                , endTime
                ,channel+""
                ,1
                ,30
                ,new Handler(){
                    @Override
                    public void handleMessage(@NonNull Message msg) {
                        super.handleMessage(msg);
                        Log.i("TAG","what-" + msg.what);
                        if (msg.what == 0) {
                            List<RecordInfo> list = (List<RecordInfo>) msg.obj;
                            if ( list.size()>0) {
                                for (int j = 0; j < list.size(); j++) {
//                                    Log.i("TAG","list_time-" + DateUtil.getDateToString(Long.valueOf(list.get(j).getStartTime()),"HH:mm:ss"));
                                    String s = DateUtil.getDateToString(Long.valueOf(list.get(j).getStartTime()),"HH:mm");
                                    if (!containHour.equals("") && s.substring(0,2).contains(containHour.substring(0,2))){
                                        mList.add(new RecordGroupItem(new RecordGroupItem.ItemInfo(containHour,containHour, list.get(j))));
//                                        Log.i("TAG","addItem-" + containHour);
                                    } else {
                                        containHour = s.substring(0,2) + ":00";
                                        mList.add(new RecordGroupItem(true,containHour));
                                        mList.add(new RecordGroupItem(new RecordGroupItem.ItemInfo(containHour,containHour , list.get(j))));
                                        Log.i("TAG","addHead-" + containHour);
                                    }

                                }


                                if (list.size() !=0) {
//                                    binding.lkRcv.init(mList
//                                            ,sac);
                                    binding.lkRcv.init(mList);
                                }

                            } else {
                                mList.clear();
//                                binding.lkRcv.init(mList
//                                        ,sac);
                                binding.lkRcv.init(mList);
                            }

                        } else if (msg.what == -1) {
                            mList.clear();
//                            binding.lkRcv.init(mList
//                                    ,sac);
                            binding.lkRcv.init(mList);
                            toast("未获取数据");
                        }
                        dismissLoadingDialog();
                    }
                });
    }

    long day = 24 * 60 * 60 * 1000;

    private void showDatePickDialog() {
        CustomDatePickerDialogFragment fragment = new CustomDatePickerDialogFragment();
        fragment.setOnSelectedDateListener(this);
        Bundle bundle = new Bundle();
        Calendar currentDate = Calendar.getInstance();
        currentDate.setTimeInMillis(System.currentTimeMillis());
        currentDate.set(Calendar.HOUR_OF_DAY,0);
        currentDate.set(Calendar.MINUTE,0);
        currentDate.set(Calendar.SECOND,0);
        currentDate.set(Calendar.MILLISECOND,0);
        bundle.putSerializable(CustomDatePickerDialogFragment.CURRENT_DATE,currentDate);


        long start = currentDate.getTimeInMillis() - day * 365 *20;
        long end = currentDate.getTimeInMillis() - day;
        Calendar startDate = Calendar.getInstance();
        startDate.setTimeInMillis(start);
        Calendar endDate = Calendar.getInstance();
        endDate.setTimeInMillis(end);
        bundle.putSerializable(CustomDatePickerDialogFragment.START_DATE,startDate);
        bundle.putSerializable(CustomDatePickerDialogFragment.END_DATE,currentDate);

        fragment.setArguments(bundle);
        fragment.show(getSupportFragmentManager(),CustomDatePickerDialogFragment.class.getSimpleName());
    }

    @Override
    public void onSelectedDate(int year, int monthOfYear, int dayOfMonth) {
//        Toast.makeText(this,year+"年"+(monthOfYear+1)+"月"+dayOfMonth+"日",Toast.LENGTH_SHORT).show();
        binding.tvDate.setText(year+"/" + (monthOfYear+1) + "/" + dayOfMonth);
        dayBefore = DateUtil.dateDiff(year+"-" + (monthOfYear+1) + "-" + dayOfMonth
                ,DateUtil.getSeveralBefore(dayBefore).substring(0,10),"yyyy-MM-dd");
        getRecordList(getIntent().getStringExtra("devId"),getIntent().getStringExtra("cameraPwd")
                ,DateUtil.getSeveralBefore(dayBefore).substring(0,10) + " 00:00:00"
                ,DateUtil.getSeveralBefore(dayBefore).substring(0,10) + " 23:59:59");
        if ((year+"-" + (monthOfYear+1) + "-" + dayOfMonth).equals(DateUtil.getNowTime().substring(0,10))) {
            binding.ivNext.setImageResource(R.drawable.hzkl_day_next_no);
            binding.ivNext.setClickable(false);
        } else {
            binding.ivNext.setImageResource(R.drawable.hzkl_day_next_click);
            binding.ivNext.setClickable(true);
        }
    }

    private class ElemeSecondaryAdapterConfig implements
            ILinkageSecondaryAdapterConfig<RecordGroupItem.ItemInfo> {

        private Context mContext;
        private Activity activity;

        public void setContext(Context context) { mContext = context; }

        public void setActivity(Activity activity) {
            this.activity = activity;
        }

        @Override
        public void onBindViewHolder(LinkageSecondaryViewHolder holder, BaseGroupedItem<RecordGroupItem.ItemInfo> item) {
            ((DrawableCenterTextView) holder.getView(R.id.tv_content))
                    .setText(DateUtil.getDateToString(Long.valueOf(item.info.getRecordInfo().getStartTime())
                    ,"HH:mm:ss"));
            GridLayoutManager.LayoutParams params = (GridLayoutManager.LayoutParams) holder.getView(R.id.layout).getLayoutParams();
            params.width = activity.getWindowManager().getDefaultDisplay().getWidth() /4 - DensityUtil.dip2px(mContext,2);
            holder.getView(R.id.layout).setLayoutParams(params);
            holder.getView(R.id.layout).setOnClickListener(v -> {
                startActivity(new Intent(activity, MediaPlayActivity.class)
                        .putExtra("TYPE", MediaPlayActivity.IS_VIDEO_REMOTE_RECORD)
                        .putExtra("RESNAME" ,getIntent().getStringExtra("name"))
                        .putExtra("RESID", item.info.getRecordInfo().getId())
                        .putExtra("RESDEVICEID", item.info.getRecordInfo().getDeviceId())
                        .putExtra("RESPWD", item.info.getRecordInfo().getDeviceKey()));
            });
        }

        @Override
        public void onBindHeaderViewHolder(LinkageSecondaryHeaderViewHolder holder, BaseGroupedItem<RecordGroupItem.ItemInfo> item) {
            ((TextView) holder.getView(R.id.tv_title)).setText(item.header + "");
        }

        @Override
        public void onBindFooterViewHolder(LinkageSecondaryFooterViewHolder holder, BaseGroupedItem<RecordGroupItem.ItemInfo> item) {

        }

        @Override
        public int getGridLayoutId() { return 0; }

        @Override
        public int getLinearLayoutId() { return R.layout.hzkl_adapter_record_time; }

        @Override
        public int getHeaderLayoutId() { return R.layout.hzkl_adapter_record_time_header; }

        @Override
        public int getFooterLayoutId() { return R.layout.hzkl_record_footview; }

        @Override
        public int getHeaderTextViewId() { return R.id.tv_title; }

        @Override
        public int getSpanCountOfGridMode() { return 4; }

    }
}
